

package com.platform.common.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.platform.common.core.oss.baen.ALiOSSStorage;
import com.platform.common.core.oss.baen.Qiniu;
import com.platform.common.core.oss.baen.TengXun;
import com.platform.common.enums.QiniuZone;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import java.util.Objects;

/**
 * 文件上传配置
 */
@Configuration
public class FileUploadConfig {


    @Autowired
    private Qiniu qiniu;

    @Autowired
    private ALiOSSStorage aliyun;

    @Autowired
    private TengXun tengXun;


    /**
     * 根据配置文件选择机房
     */
    @Bean
    public com.qiniu.storage.Configuration qiniuConfig() {
        Zone zone = null;
        if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_BEI)) {
            zone = Zone.huabei();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_DONG)) {
            zone = Zone.huadong();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.HUA_NAN)) {
            zone = Zone.huanan();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.BEI_MEI)) {
            zone = Zone.beimei();
        } else if (Objects.equals(qiniu.getZone(), QiniuZone.XIN_JIA_PO)) {
            zone = Zone.xinjiapo();
        }
        return new com.qiniu.storage.Configuration(zone);
    }

    /**
     * 构建一个七牛上传工具实例
     */
    @Bean
    public UploadManager uploadManager() {
        return new UploadManager(qiniuConfig());
    }

    /**
     * 认证信息实例
     *
     * @return
     */
    @Bean
    public Auth auth() {
        return Auth.create(qiniu.getAccessKey(), qiniu.getSecretKey());
    }

    /**
     * 构建七牛空间管理实例
     */
    @Bean
    public BucketManager bucketManager() {
        return new BucketManager(auth(), qiniuConfig());
    }


    /**
     * 构建阿里云
     */
    @Bean
    public OSS oSSClient() {
        return new OSSClientBuilder().build(aliyun.getEndpoint(), aliyun.getAccessKeyId(), aliyun.getAccessKeySecret());
    }

    /**
     * 构建腾讯云
     */
    @Bean
    public COSClient cosClient() {
        COSCredentials cred = new BasicCOSCredentials(tengXun.getAccessKeyId(), tengXun.getAccessKeySecret()); // 不传APPID也可以，APPID和ACCESSKE已经关联过
        ClientConfig clientConfig = new ClientConfig(new Region(tengXun.getCosRegion()));
        COSClient cosclient = new COSClient(cred, clientConfig);
        return cosclient;
    }

}
